package com.kangjia.jasckson;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.kangjia.jasckson.hander.DateJsonDeserializer;
import com.kangjia.jasckson.hander.DateJsonSerializer;
import com.kangjia.jasckson.hander.DecimalJsonSerializer;
import com.kangjia.jasckson.hander.LocalDateJsonDeserializer;
import com.kangjia.jasckson.hander.LocalDateJsonSerializer;
import com.kangjia.jasckson.hander.LocalDateTimeJsonDeserializer;
import com.kangjia.jasckson.hander.LocalDateTimeJsonSerializer;
import com.kangjia.jasckson.hander.LocalTimeJsonDeserializer;
import com.kangjia.jasckson.hander.LocalTimeJsonSerializer;

/**
 * jackson xml转换
 * 
 * @author sunshulin
 * 
 */
public class XmlDataMapper extends XmlMapper {

	private static final long serialVersionUID = -3318444510486292225L;

	private static XmlDataMapper xmlDataMapper;

	public XmlDataMapper() {
		super();
		JacksonXmlModule jxm = new JacksonXmlModule();
		jxm.addSerializer(Date.class, new DateJsonSerializer());
		jxm.addDeserializer(Date.class, new DateJsonDeserializer());
		jxm.addSerializer(BigDecimal.class, new DecimalJsonSerializer());
		jxm.addSerializer(LocalDate.class, new LocalDateJsonSerializer());
		jxm.addDeserializer(LocalDate.class, new LocalDateJsonDeserializer());
		jxm.addSerializer(LocalDateTime.class, new LocalDateTimeJsonSerializer());
		jxm.addDeserializer(LocalDateTime.class, new LocalDateTimeJsonDeserializer());
		jxm.addSerializer(LocalTime.class, new LocalTimeJsonSerializer());
		jxm.addDeserializer(LocalTime.class, new LocalTimeJsonDeserializer());
		this.setSerializationInclusion(Include.NON_NULL);
		this.registerModule(jxm);
	}

	public static XmlDataMapper getInstance() {
		if (xmlDataMapper == null) {
			synchronized (DataMapper.class) {
				xmlDataMapper = new XmlDataMapper();
			}
		}
		return xmlDataMapper;
	}

	public static <T> String write(T t) {
		try {
			return getInstance().writeValueAsString(t);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T read(String json, Class<T> clazz) {
		try {
			return getInstance().readValue(json.getBytes(), clazz);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
